package com.xclink.wechat.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xclink.common.utils.BaseLogger;
import com.xclink.wechat.service.CustomerService;
import com.xclink.wechat.service.TokenService;
import com.xclink.wechat.service.WxTokenService;
import com.xclink.wechat.service.core.CoreService;
import com.xclink.wechat.utils.SignUtil;

@RestController
@RequestMapping("wx")
public class WxCoreController extends BaseLogger {
	@Autowired
	private CoreService coreService;
	@Autowired
	private WxTokenService wxTokenService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	CustomerService customerService;

	// 验证是否来自微信服务器的消息
	/**
	 * @param signature
	 *            签名
	 * @param nonce
	 *            随机数
	 * @param timestamp
	 *            时间戳
	 * @param echostr
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET, produces = { "text/plain;charset=UTF-8" })
	public String checkSignature(@RequestParam(value = "signature", required = false) String signature,
			@RequestParam(value = "nonce", required = false) String nonce,
			@RequestParam(value = "timestamp", required = false) String timestamp,
			@RequestParam(value = "echostr", required = false) String echostr) {
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			logger.info("接入成功");
			System.out.println("接入成功");
			return echostr;
		}
		System.out.println("接入失败");
		logger.error("接入失败");
		return "";
	}

	// 调用核心业务类接收消息、处理消息跟推送消息
	@RequestMapping(value = "", method = RequestMethod.POST)
	public String post(HttpServletRequest req) {
		String respMessage = coreService.processRequest(req);
		return respMessage;
	}

	// 获取服务器上的 AccessToken
	@RequestMapping(value = "getAccessToken", method = RequestMethod.GET)
	public String getAccessToken() {
		Date date = new Date();
		String access_token = wxTokenService.getAccessToken();
		// 存储在数据库中
		tokenService.updateAccessToken(access_token, date);
		return access_token;
	}

	// 获取本地AccessToken,如果失效就去获取服务器的AccessToken
	@RequestMapping(value = "getLocalAccessToken", method = RequestMethod.GET)
	public String getLocalAccessToken() {
		String accessToken = tokenService.LocalAccessToken();
		return accessToken;
	}
	@RequestMapping(value = "sendMessage", method = RequestMethod.GET)
	public String sendCustomerServiceMessage( String openId){
//		String openId="oayb30nyXESR7rpNqV5CzZ7DwTzI";
		String content="哈哈哈哈哈！你来打我呀！！！！！！";
		return customerService.sendCustomerServiceMessage(openId, content);
	}
}
